package com.merry.sb.redis;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

@Configuration
public class RedisConfig {

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter listenerAdapter) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);

        // 设置监听器
        ChannelTopic topic = new ChannelTopic("myChannel");
        //订阅topic，这段代码的意思就是，将【MyRedisMessageListener】监听器，订阅到 【topic】 频道。
        container.addMessageListener(listenerAdapter, topic);
        //退订topic，
        container.removeMessageListener(listenerAdapter,topic);

        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(MyRedisMessageListener myRedisMessageListener) {
        return new MessageListenerAdapter(myRedisMessageListener);
    }
}
